package com.lbs.jiepiaisi.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
/**
 *
 * 时间：2018/1/9 13:50
 * 作用：周边导航
 */
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.google.gson.Gson;
import com.lbs.jiepiaisi.R;
import com.lbs.jiepiaisi.adapter.AroundLocationListAdapter;
import com.lbs.jiepiaisi.adapter.LocationListAdapter;
import com.lbs.jiepiaisi.adapter.SearchLocationListAdapter;
import com.lbs.jiepiaisi.adapter.SearchRecordListAdapter;
import com.lbs.jiepiaisi.base.BaseActivity;
import com.lbs.jiepiaisi.bean.AroundIconBean;
import com.lbs.jiepiaisi.bean.PoiData;
import com.lbs.jiepiaisi.bean.SearchRecord;
import com.lbs.jiepiaisi.bean.TrackEntity;
import com.lbs.jiepiaisi.manager.SharePreferenceManager;
import com.lbs.jiepiaisi.utils.Constant;
import com.lbs.jiepiaisi.view.WaitingDialogControll;

import java.util.ArrayList;
import java.util.List;

public class AroundLocationActivity extends BaseActivity implements AroundLocationListAdapter.OnItemClickListener, View.OnClickListener, TextWatcher, AMapLocationListener, PoiSearch.OnPoiSearchListener,SearchRecordListAdapter.OnItemClickListener {
    private static final String TAG = "AroundLocationActivity";

    private RecyclerView mTabRv;

    private RecyclerView mSearchRv;

    private RecyclerView mLocationRv;

    private TextView mSearchTv;

    private TextView mClearHistoryTV;

    private TextView mNoHistoryTV;

    private EditText mSearchEt;

    private ImageView iv;

    private AroundLocationListAdapter mAroundLocationListAdapter;

    List<AroundIconBean> mAroundIconBeanList;

    public SharePreferenceManager mSharePreference = null;

    private SearchRecord mSearchRecord;

    private SearchRecordListAdapter mSearchRecordListAdapter;

    //声明mlocationClient对象
    public AMapLocationClient mlocationClient;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;

    AMapLocation aMapLocation = null;

    private ArrayList<PoiItem> mData = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_around_location);
        findView();
        setListener();
        initLocation();
    }

    public void findView() {
        mTabRv = (RecyclerView) findViewById(R.id.tab_rv);
        mTabRv.setLayoutManager(new GridLayoutManager(this, 4));
        mSearchRv = (RecyclerView) findViewById(R.id.search_rv);
        mSearchRv.setLayoutManager(new LinearLayoutManager(this));
        mSearchTv = (TextView) findViewById(R.id.tv_search);
        mAroundIconBeanList = getAroundIconBean();
        mAroundLocationListAdapter = new AroundLocationListAdapter(this, mAroundIconBeanList);
        mTabRv.setAdapter(mAroundLocationListAdapter);
        mSearchEt = (EditText) findViewById(R.id.edit_search);
        mClearHistoryTV = (TextView) findViewById(R.id.tv_clear_record);
        mNoHistoryTV = (TextView) findViewById(R.id.tv_no_record);
        mLocationRv = (RecyclerView)findViewById(R.id.location_rv);
        iv = findViewById(R.id.iv);
        mLocationRv.setLayoutManager(new LinearLayoutManager(this));

    }

    public void setListener() {
        mAroundLocationListAdapter.setOnItemClickListener(this);
        mSearchTv.setOnClickListener(this);
        mSearchEt.addTextChangedListener(this);
        mClearHistoryTV.setOnClickListener(this);
        iv.setOnClickListener(this);
    }

    public void init() {
        mSharePreference = SharePreferenceManager.getInstance(this);
        String recordResult = mSharePreference.getString(Constant.ACCOUNT_SEARCH_HISTORY, "");
        if (!"".equals(recordResult)) {
            mSearchRecord = new Gson().fromJson(recordResult, SearchRecord.class);
            loadSearchHistory();
        } else {
            noSearchHistory();
        }


    }

    public void initLocation() {
        mlocationClient = new AMapLocationClient(this);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位监听
        mlocationClient.setLocationListener(this);
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setOnceLocation(true);
        //设置定位参数
        mlocationClient.setLocationOption(mLocationOption);
        // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
        // 注意设置合适的定位时间的间隔（最小间隔支持为1000ms），并且在合适时间调用stopLocation()方法来取消定位请求
        // 在定位结束后，在合适的生命周期调用onDestroy()方法
        // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
        //启动定位
        mlocationClient.startLocation();
    }

    @Override
    protected void onResume() {
        super.onResume();
        init();

    }

    @Override
    protected void onPause() {
        super.onPause();

    }

    @Override
    protected void onDestroy() {

        super.onDestroy();
        mlocationClient.stopLocation();

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

    }


    public List<AroundIconBean> getAroundIconBean() {
        List<AroundIconBean> aroundIconBeanList = new ArrayList<>();
        aroundIconBeanList.add(new AroundIconBean("酒店", R.mipmap.near_hotel));
        aroundIconBeanList.add(new AroundIconBean("加油站", R.mipmap.near_gasstation));
        aroundIconBeanList.add(new AroundIconBean("公交站", R.mipmap.near_busstation));
        aroundIconBeanList.add(new AroundIconBean("银行", R.mipmap.near_bank));
        aroundIconBeanList.add(new AroundIconBean("超市", R.mipmap.near_shopping));
        aroundIconBeanList.add(new AroundIconBean("美食", R.mipmap.near_food));
        aroundIconBeanList.add(new AroundIconBean("医院", R.mipmap.near_hospital));
        aroundIconBeanList.add(new AroundIconBean("停车场", R.mipmap.near_parking));
        return aroundIconBeanList;
    }

    @Override
    public void onItemClick(View view, int position) {
        //点击导航
        if(view.getId() == R.id.lin_out){
            toPoiActivity(mAroundIconBeanList.get(position).getDes());
        }else if(view.getId() == R.id.ll_item){ //点击历史记录
            Intent intent = new Intent(AroundLocationActivity.this,PoiAroundSearchActivity.class);
            intent.putExtra("keyWord",mSearchRecord.getSearchRecords().get(position).getTitle());
            intent.putExtra("isSearch",true);
            intent.putExtra("resultView",mSearchRecord.getSearchRecords().get(position));
            startActivity(intent);
        }

    }

    @Override
    public void onItemLongClick(View view, int position) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_search:
                if(mSearchTv.getText().toString().contains("搜索")){
                    if ("".equals(mSearchEt.getText().toString())) {
                        Toast.makeText(this, "请输入搜索内容", Toast.LENGTH_SHORT).show();
                        break;
                    }
                    toPoiActivity(mSearchEt.getText().toString());

                }else {
                    mSearchEt.setText("");
                    searchNoAroundView();
                }

                break;
            case R.id.tv_clear_record:
                clearSearchHistory();
                break;
            case R.id.iv:
                if ("".equals(mSearchEt.getText().toString())) {
                    Toast.makeText(this, "请输入搜索内容", Toast.LENGTH_SHORT).show();
                    break;
                }
                if(mData == null || mData.size() ==0){
                    Toast.makeText(this, "未查询到搜索内容", Toast.LENGTH_SHORT).show();
                    break;
                }
                Intent intent = new Intent(AroundLocationActivity.this, PoiAroundSearchActivity.class);
                intent.putExtra("keyWord", mSearchEt.getText().toString());
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    private void toPoiActivity(String keyWord) {
        Intent intent = new Intent(this, PoiAroundSearchActivity.class);
        intent.putExtra("keyWord", keyWord);
        startActivity(intent);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        String input =  s.toString();
        mData.clear();
        if ((!"".equals(input)) && aMapLocation != null) {
            doSearchQuery(input);
            mSearchTv.setText("取消");
        }
        if("".equals(input)){
            mSearchTv.setText("搜索");
            init();
        }
    }

    private void noSearchHistory() {
        mNoHistoryTV.setVisibility(View.VISIBLE);
        mClearHistoryTV.setVisibility(View.GONE);
        mSearchRv.setVisibility(View.GONE);
    }

    private void loadSearchHistory() {
        mTabRv.setVisibility(View.VISIBLE);
        mLocationRv.setVisibility(View.GONE);
        mNoHistoryTV.setVisibility(View.GONE);
        mClearHistoryTV.setVisibility(View.VISIBLE);
        mSearchRecordListAdapter = new SearchRecordListAdapter(this, mSearchRecord.getSearchRecords());
        mSearchRv.setVisibility(View.VISIBLE);
        mSearchRv.setAdapter(mSearchRecordListAdapter);
        mSearchRecordListAdapter.setOnItemClickListener(this);
    }

    private void clearSearchHistory() {
        mSharePreference.put(Constant.ACCOUNT_SEARCH_HISTORY, "");
        mSearchRecord.getSearchRecords().clear();
        init();
    }
    //附近查询到结果
    private void searchAroundView(){
        mLocationRv.setVisibility(View.VISIBLE);
        mTabRv.setVisibility(View.GONE);
        mNoHistoryTV.setVisibility(View.GONE);
        mClearHistoryTV.setVisibility(View.GONE);
        mSearchRv.setVisibility(View.GONE);

    }
    //附近查询不到到结果
    private void searchNoAroundView(){
        mLocationRv.setVisibility(View.GONE);
        mTabRv.setVisibility(View.VISIBLE);
        init();
    }

    private void addToHistory(PoiData value) {
        if (mSearchRecord == null) {
            mSearchRecord = new SearchRecord();
        }
        List<PoiData> resultsOld = mSearchRecord.getSearchRecords();
        if (resultsOld == null) {
            ArrayList<PoiData> results = new ArrayList<>();
            results.add(0, value);
            mSearchRecord.setSearchRecords(results);

        } else {
            if (resultsOld.size() > 9) {
                resultsOld.remove(resultsOld.size() - 1);
            }
            if (isCanAdd(value)) {
                resultsOld.add(0, value);
                mSearchRecord.setSearchRecords(resultsOld);
            }

        }
        if (mSearchRecordListAdapter == null) {
            mSearchRecordListAdapter = new SearchRecordListAdapter(this, mSearchRecord.getSearchRecords());
            mSearchRv.setAdapter(mSearchRecordListAdapter);
        } else {
            mSearchRecordListAdapter.notifyDataSetChanged();
        }
        mSearchRecordListAdapter.setOnItemClickListener(this);
        String record = new Gson().toJson(mSearchRecord);
        mSharePreference.put(Constant.ACCOUNT_SEARCH_HISTORY, record);
        Log.e(TAG, record);
    }

    private boolean isCanAdd(PoiData value) {
        for (PoiData result : mSearchRecord.getSearchRecords()) {
            if (result.getTitle().equals(value.getTitle())) {
                return false;
            }

        }
        return true;
    }


    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        Log.e("TAG", "地理位置信息：" + aMapLocation);
        this.aMapLocation = aMapLocation;

    }

    SearchLocationListAdapter searchRecordListAdapter;
    @Override
    public void onPoiSearched(PoiResult result, int rcode) {
        final PoiResult resultFinal = result;
        if (rcode == AMapException.CODE_AMAP_SUCCESS) {
            if (resultFinal != null && resultFinal.getQuery() != null && resultFinal.getPois() != null  && resultFinal.getPois().size() >0) {// 搜索poi的结果
                searchRecordListAdapter = new SearchLocationListAdapter(this,resultFinal.getPois());
                mData = resultFinal.getPois();
                mLocationRv.setAdapter(searchRecordListAdapter);
                searchRecordListAdapter.setOnItemClickListener(new SearchLocationListAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        PoiData poiData = new PoiData(resultFinal.getPois().get(position).getLatLonPoint().getLatitude(),resultFinal.getPois().get(position).getLatLonPoint().getLongitude(),resultFinal.getPois().get(position).getTitle(),resultFinal.getPois().get(position).getSnippet(),resultFinal.getPois().get(position).getDistance());
                        addToHistory(poiData);
                        Intent intent = new Intent(AroundLocationActivity.this,PoiAroundSearchActivity.class);
                        intent.putExtra("keyWord",resultFinal.getPois().get(position).getTitle());
                        intent.putExtra("isSearch",true);
                        intent.putExtra("resultView",poiData);
                        startActivity(intent);
                    }

                    @Override
                    public void onItemLongClick(View view, int position) {

                    }
                });
                searchAroundView();
            }else {
                searchNoAroundView();
            }
        }else {
            searchNoAroundView();
        }
    }

    @Override
    public void onPoiItemSearched(PoiItem result, int rcode) {
        if (rcode == AMapException.CODE_AMAP_SUCCESS) {

        }
    }
/**
     * 开始进行poi搜索
     */
    /**
     * 开始进行poi搜索
     */
    protected void doSearchQuery(String keyWord) {
        int currentPage = 0;
        PoiSearch.Query query = new PoiSearch.Query(keyWord, "", aMapLocation.getCity());// 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
        query.setPageSize(20);// 设置每页最多返回多少条poiitem
        query.setPageNum(currentPage);// 设置查第一页
        LatLonPoint lp = new LatLonPoint(aMapLocation.getLatitude(), aMapLocation.getLongitude());
        PoiSearch poiSearch = new PoiSearch(this, query);
        poiSearch.setOnPoiSearchListener(this);
        poiSearch.setBound(new PoiSearch.SearchBound(lp, 1000, true));//
        // 设置搜索区域为以lp点为圆心，其周围5000米范围
        poiSearch.searchPOIAsyn();// 异步搜索
    }





}
